// pages/index/search.js
import debounce from '../../utils/debounce'
import { search } from '../../utils/apis'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    inputShowed: false,
    inputVal: '',
    page: 0,
    size: 10,
    hasMore: true,
    loading: false
  },
  showInput: function() {
    this.setData({
      inputShowed: true
    })
  },
  hideInput: function() {
    this.setData({
      inputVal: '',
      inputShowed: false
    })
  },
  clearInput: function() {
    this.setData({
      inputVal: ''
    })
  },
  inputTyping: function(e) {
    var { value } = e.detail
    this.setData({
      list: [],
      inputVal: value,
      page: 0,
      hasMore: true,
      loading: false
    })
    if (value) {
      this.loadData()
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options.siteId)
    this.setData({
      siteId: options.siteId
    })
    this.inputTyping = debounce(this.inputTyping, 300)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var { loading, hasMore } = this.data
    if (hasMore && !loading) {
      this.loadData()
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},
  loadData() {
    var that = this
    var { loading, page, inputVal, size, siteId } = this.data
    if (loading) {
      return
    }
    that.setData({
      loading: true
    })

    search({
      siteId,
      page,
      size,
      inputVal
    })
      .then(result => {
        var { list } = that.data
        that.setData({
          loading: false,
          list: list ? list.concat(result.stores) : result.stores,
          hasMore: result.count > (that.data.page + 1) * 10,
          page: +page + 1
        })
      })
      .catch(err => {})
  }
})
